package com.cartagena.financo.controller;

import java.util.Date;
import java.util.List;

import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;

import com.cartagena.financo.model.Transaction;
import com.cartagena.financo.repository.TransactionRepository;
import com.cartagena.financo.util.CategorySum;
import com.cartagena.financo.util.DateUtil;
import com.cartagena.financo.util.TransactionUtil;
import com.cartagena.vraptor.extjs.ExtJSJson;

@Resource
public class SumController {

    private final Result result;
    private final TransactionRepository repository;

    public SumController(Result result, TransactionRepository repository) {
        this.result = result;
        this.repository = repository;
    }

    @Path("/sum/category")
    public void category(Date begin, Date end) {
        if(begin == null) {
            begin = DateUtil.getDefaultDayBegin();
        }
        if(end == null) {
            end = DateUtil.getDefaultDayEnd();
        }  
        
        List<Transaction> transactions = repository.listByPeriod(begin, end);        
        List<CategorySum> result  = TransactionUtil.sumGrouped(transactions);

        this.result.use(ExtJSJson.class).from(result).success().serialize();

    }

}
